import urllib.parse
from mblog import Mblog
import requests
import time

headers = {
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
}


# next_page = 'https://m.weibo.cn/api/container/getIndex?containerid=100103type=60&q=#'+keyword+'#&t=10&isnewpage=1&extparam=cate=0&pos=0&realpos=1&flag=2&filter_type=realtimehot&c_type=31&display_time=1584171716&luicode=10000011&lfid=106003type=25&t=3&disable_hot=1&filter_type=realtimehot&page_type=searchall&page=2'

def resolve_mblog(response):
    list = []
    if response.status_code == 200 and response.json().get('ok') == 1:
        cards = response.json().get('data').get('cards')
        for card in cards:
            if card['card_type'] == 9:
                list.append(Mblog(card))
    return list
def search_hot_mblog(keyword,page=1):
    base_url = 'https://m.weibo.cn/api/container/getIndex?'
    params = {
        'containerid': '100103type=60&q=#' + keyword + '#&t=10',
        'isnewpage': '1',
        'extparam': 'cate=0&pos=0&realpos=1&flag=1&filter_type=realtimehot&c_type=31&display_time=' + str(time.time()),
        'luicode': '10000011',
        'lfid': '100103type=1',
        'page_type': 'searchall'
    }
    detail_url = base_url + urllib.parse.urlencode(params)
    if page > 1:
        detail_url = detail_url +'page%s'%page
    detail = requests.get(detail_url, headers=headers)

    return resolve_mblog(detail)


def search_real_time_mblog(keyword, page):
    base_url = 'https://m.weibo.cn/api/container/getIndex?'
    headers = {
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
    }
    params = {
        'containerid': '100103type=61&q=#' + keyword + '#&t=10',
        'isnewpage': '1',
        'extparam': 'cate=0&pos=0&realpos=1&flag=2&filter_type=realtimehot&c_type=31&display_time='+str(time.time()),
        'luicode': '10000011',
         'lfid': '106003type=25&t=3&disable_hot=1&filter_type = realtimehot',
         'page_type': 'searchall',
         'page': str(page)
    }
    real_time_url = base_url+urllib.parse.urlencode(params)
    res = requests.get(real_time_url,headers)
    return resolve_mblog(res)
